package org.leiyang.netty.listener;

import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.leiyang.common.holder.MsgServerAndClientHolder;

import java.util.Objects;

/**
 * 监听客户端上线/下线
 */
@Service
public class MsgClientChangeListener implements IClientChangeListener {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final MsgServerAndClientHolder msgServerAndClientHolder;

    public MsgClientChangeListener(MsgServerAndClientHolder msgServerAndClientHolder) {
        this.msgServerAndClientHolder = msgServerAndClientHolder;
    }

    @Override
    public void newClient(String clientId, ChannelHandlerContext ctx) {
        //暂时未使用到
    }

    @Override
    public void loseClient(ChannelHandlerContext ctx) {
        String clientId = msgServerAndClientHolder.gotClientIdByChannel(ctx.channel());
        if(Objects.nonNull(clientId)) {
            msgServerAndClientHolder.removeOfflineClient(clientId)
                    .subscribe(remove -> logger.info("移除ClientId:[{}]结果: {}", clientId, remove ? "成功" : "失败"));
        }
    }
}